package com.itmk.config.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.itmk.utils.ResultVo;
import org.springframework.security.authentication.*;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import com.itmk.config.security.exception.CustomerAuthenionException;

import org.springframework.security.core.AuthenticationException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component("loginFailureHandler")  // 建议改为小写开头的bean名称
public class LoginFailureHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request,HttpServletResponse response,AuthenticationException e) throws IOException {
        int code = 500;
        String msg = "";
        // 按从具体到一般的顺序判断
        if (e instanceof BadCredentialsException) {
            msg = "用户密码错误";
        } else if (e instanceof DisabledException) {
            msg = "账户被禁用，请联系管理员";
        } else if (e instanceof LockedException) {
            msg = "账户被锁定，请联系管理员";
        } else if (e instanceof AccountExpiredException) {
            msg = "账户已过期";
        } else if (e instanceof CredentialsExpiredException) {
            msg = "密码已过期，请修改密码";
        }
        else if(e instanceof InsufficientAuthenticationException){
            msg = "无权限访问资源";
        }else if(e instanceof  InternalAuthenticationServiceException){
            msg = "账户不存在，登录失败";
        }else if(e instanceof CustomerAuthenionException){
            code = 600;
            msg = e.getMessage();
        }
        else {
            msg = "登录失败: " + e.getClass().getSimpleName();  // 添加异常类型便于调试
        }

        String json = JSONObject.toJSONString(
                new ResultVo<>(msg, code, null),
                SerializerFeature.DisableCircularReferenceDetect
        );

        response.setContentType("application/json;charset=UTF-8");
        try (ServletOutputStream out = response.getOutputStream()) {
            out.write(json.getBytes("UTF-8"));
        }
    }
}
